/**
 * 
 */
package co.edu.udistrital.analyzer.business.services.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import co.edu.udistrital.analyzer.business.orm.model.User;
import co.edu.udistrital.analyzer.business.services.UsersService;

/**
 * @author Alejo
 *
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
	
	/**
	 * The log4j Logger
	 */
	private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private UsersService usersService;


	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@Override
	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException {
		LOGGER.info("Trying to fetch user with login: " + login);
		final User user = usersService.findUserByLogin(login);
		if (user == null) {
			throw new UsernameNotFoundException("User not found");
		}
		 
		// sample roles 
		Collection<GrantedAuthority> adminAuthorities = new ArrayList<GrantedAuthority>();
		adminAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		// sample users with roles set
		return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, adminAuthorities);
	}

}
